<template lang="html">
    <div class="car_screen_container">
        <!-- <lty-card title='实时监控' style="height: 100%;"> -->
        <!-- {{ playList }} -->
        <!-- {{ expandedKeys }} -->
        <!-- outEqCodeList :{{props.outEqCodeList}} -->
        <div class="car_screen1">
            <div class="car_screen_status">
                <span :class="{ 'active': state.onlineStatus === '99' }" @click="handleCheckStatus('99')">全部<i>{{
                    state.allCarCount }}</i></span>
                <span :class="{ 'active': state.onlineStatus === '1' }" @click="handleCheckStatus('1')">在线<i>{{
                    state.onLineCarCount }}</i></span>
                <span :class="{ 'active': state.onlineStatus === '0' }" @click="handleCheckStatus('0')">离线<i>{{
                    state.offLineCarCount }}</i></span>
            </div>
            <div class="car_screen_filter">
                <a-input v-model:value="state.searchValue" placeholder="请输入" addon-before="摄像头名称" allow-clear></a-input>

            </div>
        </div>

        <div class="video-tree">
            <div class="companey_name">充电站</div>

            <a-tree blockNode v-model:expandedKeys="expandedKeys" :selectable="false"
                :auto-expand-parent="autoExpandParent" :tree-data="state.treeData" @expand="onExpand" :fieldNames="{
                    children: 'children',
                    title: 'label',
                    key: 'id',
                }">
                <template #switcherIcon="{ switcherCls }">
                    <CaretDownOutlined :class="switcherCls" />
                </template>
                <template #title="{ label, id, online, type, total, onlineTotal }">
                    <div @click="clickHandel(id, type)" @dblclick="onSelect2(id)"
                        :class="{ video_item: true, offline: type == 'video' && !online, active: selectedKeys.includes(id) }"
                        :id='id'>
                        <span v-if="label && label.indexOf(state.searchValue) > -1">
                            <!-- {{ label }} -->
                            {{ label.substr(0, label.indexOf(state.searchValue)) }}
                            <span style="color: #f50">{{ state.searchValue }}</span>
                            {{ label.substr(label.indexOf(state.searchValue) + state.searchValue.length) }}
                        </span>
                        <span v-else>{{ label }}</span>
                        <span v-if="type == 'site'" class="total_num">( <span>{{ onlineTotal }}</span> / {{ total }}
                            )</span>
                    </div>
                </template>
            </a-tree>
        </div>
        <!-- </lty-card> -->

    </div>
</template>

<script lang="js" setup>
import LtyCard from "../LTYCard";
import { defineComponent, onMounted, reactive, ref, watch, nextTick, defineEmits } from "vue";
import { DownOutlined, CaretDownOutlined } from '@ant-design/icons-vue';
import { treeList } from "@/service/api";
import { getVideoPlayUrl } from "@/utils";
// import _ from 'lodash';
const props = defineProps({
    playList: {
        default: () => [],
        type: Array
    },
    outEqCodeList: {
        default: () => [],
        type: Array
    },
})
const emit = defineEmits(['changChannle'])
const state = reactive({
    allCarCount: 0, // 全部车辆数
    onLineCarCount: 0, // 在线车辆数
    offLineCarCount: 0, // 离线车辆数
    carStatus: '1', // 车辆在线状态
    // type: '1',
    searchValue: '',

    onlineStatus: '99',
    treeData: [],  //左边组织架构书  原始数据
    treeSelect: {}, //选中的节点

});
const expandedKeys = ref([]);
const selectedKeys = ref([]);
const autoExpandParent = ref(true);

let dataList = [];  //组织架构的扁平化
onMounted(() => {
    init('first');
})
const init = (type) => {
    // 获取摄像头tree
    treeList().then(res => {
        if (res.status =='000_0000_0000') {
            // message.success(state.modalType == 'new'?'添加成功':'编辑成功');
            // handleCancel()
            state.allCarCount = res.data.totalCt;
            state.onLineCarCount = res.data.onlineCt;
            state.offLineCarCount = res.data.offlineCt;
            // state.treeData = res.data.yardStationList;

            state.treeData = treeDataFormat(res.data.yardStationList);
            // console.log(props.outEqCodeList,'props.outEqCodeList--tree init');
            if (props.outEqCodeList) {

                outEqCodeListChange();
                // return
            } else if (type == 'first' && res.data.yardStationList.filter(item => item.equipList.length)) {
                // 默认第一个展开
                expandedKeys.value = [res.data.yardStationList.filter(item => item.equipList.length)[0]?.id];
                // autoExpandParent.value = false;
            }
            // console.log(expandedKeys.value,'expandedKeys.value');
        }
    })
}
//treeData转换 
const treeDataFormat = (data, parentKey, parentName) => {
    const tree = []
    data.forEach(item => {
        let obj = {
            ...item,
            key: item.id,
            label: item.eqName || item.name,
            type: item.eqName ? 'video' : 'site',
            total: 0,
            onlineTotal: 0,
        }
        if (item.equipList && item.equipList.length) {
            obj.children = treeDataFormat(item.equipList, item.id, item.name);

            obj.total = obj.children.length;
            obj.onlineTotal = obj.children.filter(item => item.online == 1).length;
        }
        if (obj.type == 'video') {
            obj.parentKey = parentKey;
            obj.yardStationName = parentName;
            if (obj.online == state.onlineStatus || state.onlineStatus == '99') {
                tree.push(obj);
                dataList.push(obj);
            }
        } else {
            // obj.total:0,
            // obj.onlineTotal:0,
            if (obj.total != 0) {
                tree.push(obj);
                dataList.push(obj);
            }

        }

    })
    return tree
}
// 外部传值 直接播放该设备视屏
const outEqCodeListChange = () => {
    // console.log(props.outEqCodeList,'props.outEqCodeList');
    if (props.outEqCodeList.length && dataList.length) {
        let expandList = []
        props.outEqCodeList.map((item, index) => {
            let obj = dataList.find(el => el.eqCode == item);
            // if(index ===0)expandedKeys.value = [obj.parentKey];
            if (obj.online == 1) {
                // 触发点击播放
                onSelect2(obj.id);
                if (!expandList.includes(obj.parentKey)) expandList.push(obj.parentKey)

            }
        })

        expandedKeys.value = expandList;
    }
}

// 单击 如果是场站 展开 收起
const clickHandel = (id, type) => {
    if (type == 'site') {
        if (expandedKeys.value.includes(id)) {
            expandedKeys.value = expandedKeys.value.filter(item => item != id)
            autoExpandParent.value = true;
        } else {
            expandedKeys.value.push(id);
            autoExpandParent.value = false;
        }
    }
}
// 双击播放视屏
const onSelect2 = (id) => {
    if (selectedKeys.value.includes(id)) {
        // selectedKeys.value = selectedKeys.value.filter(item=>item != id)
    } else {
        let obj = dataList.find(item => item.id == id);
        // if(obj.type=="video" && obj.online){
        if (obj.type == "video") {
            obj.playUrl = getVideoPlayUrl(obj.eqCode);
            emit('changChannle', obj)
            // selectedKeys.value.push(id);

            // changChannle()
            // console.log(3333,getVideoPlayUrl(obj.eqCode));
        }
    }
    // selectedKeys.value= [id];
}
// const changChannle=(id) => {
// 	let list = [];
// 	selectedKeys.value.map(keys=>{
// 		let obj= dataList.find(item=>item.id == keys);
// 		obj.playUrl = getVideoPlayUrl(obj.eqCode);
// 		if(obj){
// 			list.push(obj)
// 		}
// 	})

// 	emit('changChannle',list)
// }
const onExpand = keys => {
    expandedKeys.value = keys;
    autoExpandParent.value = false;
}
// 查看是否有外部船体的outEqCodeList
watch(() => props.outEqCodeList, value => {
    // console.log(props.outEqCodeList,'props.outEqCodeList');
    outEqCodeListChange()
}, { deep: true });
watch(() => props.playList, value => {
    // console.log('props.playList',value);
    selectedKeys.value = value.map(item => item.id)
}, { deep: true });

watch(() => state.searchValue, value => {
    const expanded2 = dataList.map(item => {
        if (item.label.indexOf(value) > -1) {
            return getParentKey(item.id, state.treeData);
        }
        return null;
    })
    const expanded = expanded2.filter((item, i, self) => item && self.indexOf(item) === i);
    expandedKeys.value = expanded;
    state.searchValue = value;
    autoExpandParent.value = true;
});
const getParentKey = (id, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
            if (node.children.some(item => item.id === id)) {
                parentKey = node.id;
            } else if (getParentKey(id, node.children)) {
                parentKey = getParentKey(id, node.children);
            }
        }
    }
    return parentKey;
};
/**
 * 选择车辆状态
 * @param {string} status 99-全部 1-在线 0-离线
 */
const handleCheckStatus = (status) => {

    state.onlineStatus = status;
    init()
    // props.onSearch && props.onSearch({
    // 	searchValue: state.searchValue,
    // 	onlineStatus: state.onlineStatus,
    // 	date: state.date
    // });
}

// 输入搜索
// const handleChangeInputItem = _.debounce(() => {
// 	const params = {
// 		type: state.type,
// 		searchValue: state.searchValue,
// 		carStatus: state.carStatus
// 	}
// }, 800)


</script>

<style lang="less" scoped>
.car_screen_container {
	width: 100%;
	height: 100%;
	// padding: 20px;
	position: relative;

	// background-color: #fff; 
	// background: rgba(0, 4, 69, 0.4);
	// border-radius: 8px;
	// border: 1px solid;
	// -o-border-image: linear-gradient(90deg, rgba(0, 130, 242, 0), #53e6ff, rgba(0, 130, 242, 0)) 1 1;
	// border-image: linear-gradient(90deg, rgba(0, 130, 242, 0), #53e6ff, rgba(0, 130, 242, 0)) 1 1;
	.video-tree {
		height: calc(100% - 120px);
		// background-color: red;
		overflow: auto;
		// padding-top: 2px;
		background: rgba(0, 4, 69, 0.4);
		border-radius: 0px 0px 8px 8px;
		border: 1px solid;

		border-image: linear-gradient(90deg, rgba(0, 130, 242, 0), #53e6ff, rgba(0, 130, 242, 0)) 1 1;

		.companey_name {
			width: 100%;
			height: 40px;
			line-height: 40px;
			background: #000445;
			border-radius: 0px 0px 100px 100px;
			font-size: 16px;
			color: #FFFFFF;
			text-align: center;
			border-bottom: 1px solid;

			border-image: linear-gradient(90deg, rgba(0, 4, 69, 0.4) 0%, rgba(0, 130, 242, 0) 10%, #53e6ff 50%, rgba(0, 4, 69, 0.4) 90%, rgba(0, 130, 242, 0)) 100% 1 1;
		}

		.video_item {
			padding: 4px
		}

		.offline {
			cursor: not-allowed;
			color: #a0b1be;
		}

		.total_num {
			margin-left: 6px;

			>span {
				color: #00cccc;
			}
		}

		.active {
			color: #00cccc;
			background: rgba(41, 214, 255, 0.1);
		}

		:deep(.nmc-tree-switcher) {

			// line-height: 32px;
			.nmc-tree-switcher-icon {
				margin-top: 10px;
			}

			svg {
				font-size: 14px;
				color: rgba(153, 153, 153, 0.9);
			}
		}

		// height: 100px
	}

	.car_screen_status {
		display: flex;
		border-radius: 6px;
		border: 1px solid #A0B1BE;
		;
		padding: 6px;
		// margin-top: 16px;

		>span {
			flex: 1;
			font-size: 14px;
			font-weight: 400;
			color: #A0B1BE;
			line-height: 14px;
			cursor: pointer;
			text-align: center;

			i {
				margin-left: 4px;
				font-style: normal;
			}

			&:nth-of-type(2) {
				border-left: 1px solid #A0B1BE;
				;
				border-right: 1px solid #A0B1BE;
				;
			}

			&.active {
				color: #fff;

				>i {
					color: #00cccc;
				}
			}
		}
	}

	.car_screen1 {
		padding: 20px;
		background: rgba(0, 4, 69, 0.4);
		margin-bottom: 10px;
		// opacity: 0.4;
		border-radius: 8px;
		border: 1px solid;

		border-image: linear-gradient(90deg, rgba(0, 130, 242, 0), #53e6ff, rgba(0, 130, 242, 0)) 1 1;

		.car_screen_filter {
			position: relative;
			// border: 1px solid rgba(221, 221, 221, 0.9);
			// border-radius: 6px;
			margin-top: 8px;
			box-sizing: border-box;
		}
	}

}
</style>